import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Slf4j
public class HttpRequestHandler extends SimpleChannelInboundHandler<FullHttpRequest> {

    private static final List<String> NO_LOG_URL = Arrays.asList("/getValues", "/", "/favicon.ico");


    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.flush();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception {
        //100 Continue
        if (HttpUtil.is100ContinueExpected(req)) {
            ctx.write(new DefaultFullHttpResponse(
                    HttpVersion.HTTP_1_1,
                    HttpResponseStatus.CONTINUE));
        }
        // 获取请求的uri
        String uri = req.uri();
        QueryStringDecoder decoder = new QueryStringDecoder(uri);
        if (!NO_LOG_URL.contains(decoder.path())) {
            log.info("请求路径:{},请求类型:{}", uri, req.method());
        }
        FullHttpResponse response = RequestControllerManager.getInstance().getRequestHandler(req.method().name(), decoder.path()).handle(req);
        if (!NO_LOG_URL.contains(decoder.path())) {
            log.info("响应内容:{}", response.content().toString(StandardCharsets.UTF_8));
        }
        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    }

}